package org.example.wumeng.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.wumeng.service.T_userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.wumeng.pojo.Result;
import org.example.wumeng.pojo.User;

import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class T_userProfileController {

    @Autowired
    private T_userService userService;

    /**
     * 获取用户详细信息
     */
    @GetMapping("/profile")
    public Result<User> getProfile(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || token.trim().isEmpty()) {
                return Result.unauthorized("未提供认证信息");
            }

            User user = userService.getUserInfo(token);
            return new Result<>(200, "获取成功", user, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.unauthorized(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户资料
     */
    @PutMapping("/profile")
    public Result<User> updateProfile(@RequestBody User user, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || token.trim().isEmpty()) {
                return Result.unauthorized("未提供认证信息");
            }

            // 获取当前用户ID
            User currentUser = userService.getUserInfo(token);
            Long userId = currentUser.getId();

            // 更新用户资料
            User updatedUser = userService.updateProfile(userId, user);
            return new Result<>(200, "更新成功", updatedUser, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新用户资料失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<Void> changePassword(@RequestBody Map<String, String> passwordData, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || token.trim().isEmpty()) {
                return Result.unauthorized("未提供认证信息");
            }

            String currentPassword = passwordData.get("currentPassword");
            String newPassword = passwordData.get("newPassword");

            if (currentPassword == null || currentPassword.trim().isEmpty()) {
                return Result.badRequest("当前密码不能为空");
            }
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.badRequest("新密码不能为空");
            }

            // 获取当前用户ID
            User currentUser = userService.getUserInfo(token);
            Long userId = currentUser.getId();

            // 修改密码
            boolean success = userService.changePassword(userId, currentPassword.trim(), newPassword.trim());
            if (success) {
                return new Result<>(200, "密码修改成功", null, null);
            } else {
                return Result.error("密码修改失败");
            }

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }

    /**
     * 上传头像
//     */
//    @PostMapping("/avatar")
//    public Result<String> uploadAvatar(@RequestBody Map<String, String> avatarData, HttpServletRequest request) {
//        try {
//            String token = request.getHeader("Authorization");
//            if (token == null || token.trim().isEmpty()) {
//                return Result.unauthorized("未提供认证信息");
//            }
//
//            String avatarUrl = avatarData.get("avatarUrl");
//            if (avatarUrl == null || avatarUrl.trim().isEmpty()) {
//                return Result.badRequest("头像URL不能为空");
//            }
//
//            // 获取当前用户ID
//            User currentUser = userService.getUserInfo(token);
//            Long userId = currentUser.getId();
//
//            // 上传头像
//            boolean success = userService.uploadAvatar(userId, avatarUrl.trim());
//            if (success) {
//                return new Result<>(200, "头像上传成功", avatarUrl, null);
//            } else {
//                return Result.error("头像上传失败");
//            }
//
//        } catch (IllegalArgumentException e) {
//            return Result.badRequest(e.getMessage());
//        } catch (RuntimeException e) {
//            return Result.badRequest(e.getMessage());
//        } catch (Exception e) {
//            return Result.error("上传头像失败: " + e.getMessage());
//        }
//    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || token.trim().isEmpty()) {
                return Result.unauthorized("未提供认证信息");
            }

            // 获取当前用户信息
            User currentUser = userService.getUserInfo(token);

            // 构造统计信息（这里可以根据实际需求添加更多统计）
            Map<String, Object> statistics = new java.util.HashMap<>();
            statistics.put("userId", currentUser.getId());
            statistics.put("username", currentUser.getUsername());
            statistics.put("registerTime", currentUser.getCreateTime());
            statistics.put("lastLoginTime", currentUser.getLastLoginTime());
            statistics.put("profileComplete", isProfileComplete(currentUser));

            return new Result<>(200, "获取成功", statistics, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.unauthorized(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 检查个人资料是否完整
     */
    private boolean isProfileComplete(User user) {
        return user.getName() != null && !user.getName().trim().isEmpty() &&
                user.getEmail() != null && !user.getEmail().trim().isEmpty() &&
                user.getPhone() != null && !user.getPhone().trim().isEmpty();
    }
}
